import { ref, onMounted, onUnmounted } from 'vue';

function useCountdown(totalSeconds) {
    const left = ref(totalSeconds);

    let timer = null;

    function startCountdown() {
        clearInterval(timer);

        timer = setInterval(() => {
            left.value--;

            if (left.value <= 0) {
                clearInterval(timer);
            }
        }, 1000);
    }

    function stopCountdown() {
        clearInterval(timer);
    }

    // 在组件挂载时开始倒计时
    onMounted(() => {
        startCountdown();
    });

    // 在组件卸载时停止倒计时
    onUnmounted(() => {
        stopCountdown();
    });

    return {
        remainingSeconds: left,
        startCountdown,
        stopCountdown,
    };

}

export default useCountdown;